package handlers

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	price, _ := strconv.Atoi(c.PostForm("price"))

	if name == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := models.Food{
		Name:  name,
		Price: price,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "food_add_" + strconv.Itoa(int(data.ID))
	var food models.Food
	models.DB.Where("id=?", data.ID).First(&food)
	cacheData, _ := json.Marshal(food)
	cache.Rdb.Set(cache.Ctx, redis_key, cacheData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))

	Offset := (page - 1) * size

	var food []models.Food

	redis_key := "food_list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(Offset).Limit(size).Find(&food)

		jsonData, _ := json.Marshal(food)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}

	var total int64
	models.DB.Model(&models.Food{}).Count(&total)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": food,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var food models.Food

	redis_key := "food_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).First(&food)

		jsonData, _ := json.Marshal(food)

		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &food)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": food,
	})
	return
}
